<template>
  <div>
    <!-- This is exam page! -->
    <!-- breadcrumb nav -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/manager' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>考试管理</el-breadcrumb-item>
        <el-breadcrumb-item>考试安排</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 查找课程：搜索框 -->
    <el-card class="search-bar">
      <el-row :gutter="20" type="flex" align="middle">
        <el-col :span="2" :offset="0">
          精准查找
        </el-col>
        <el-col :span="10" :offset="0">
          <el-input
          placeholder="请输入内容"
          v-model="searchValue"
          class="input-with-select"
          clearable>
            <el-select v-model="searchMethod" slot="prepend" placeholder="课程名称">
              <el-option label="课程名称" value="1"></el-option>
              <el-option label="学院名称" value="2"></el-option>
            </el-select>
            <el-button slot="append" icon="el-icon-search" @click="searchCourse()"></el-button>
          </el-input>
        </el-col>
      </el-row>
    </el-card>

    <!-- 课程列表 -->
    <el-card class="course-list">

      <!-- 所有的列表信息 -->
      <el-table
      :data="examTable"
      style="width: 100%">
        <!-- <el-table-column
          type="selection"
          width="50">
        </el-table-column> -->
        <!-- 创建时间 -->
        <el-table-column
          label="创建时间"
          align="center"
          prop="create_time"
          width="100">
        </el-table-column>
        <!-- 更新时间 -->
        <el-table-column
          label="更新时间"
          align="center"
          prop="update_time"
          width="100">
        </el-table-column>
        <!-- 是否安排 -->
        <el-table-column
          label="是否安排"
          align="center"
          prop="isArrange"
        >
        </el-table-column>
        <!-- 课程名 -->
        <el-table-column
          label="课程编号"
          align="center"
          prop="course_teacher_num"
        >
        </el-table-column>
        <el-table-column
          label="课程名称"
          align="center"
          prop="course_name"
          width="100">
        </el-table-column>
        <el-table-column
          label="专业"
          align="center"
          prop="class_name"
        >
        </el-table-column>
        <el-table-column
          prop="school_name"
          align="center"
          label="学院"
          width="130">
        </el-table-column>
        <el-table-column
          prop="exam_day"
          align="center"
          label="考试日期"
          width="100">
        </el-table-column>
        <el-table-column
          prop="exam_time"
          align="center"
          label="考试时间"
          width="100">
        </el-table-column>
        <el-table-column
          prop="exam_classroom"
          align="center"
          label="考试地点">
        </el-table-column>
        <el-table-column
          prop="exam_teacher_name"
          align="center"
          label="监考老师">
        </el-table-column>
        <el-table-column
          prop="credict"
          align="center"
          label="学分">
        </el-table-column>
        <el-table-column
          width="180"
          align="center"
          fixed="right"
          label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="school" @click="expandSetExamDrawer(scope.row)">安排考试</el-button>
            <el-button size="mini" type="danger" plain @click="dropExam(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页导航 -->
      <el-pagination
        background
        @current-change="handleCurrentChange"
        :page-size="10"
        layout="total, prev, pager, next"
        :total="totalCourse">
      </el-pagination>
    </el-card>

    <!-- 安排考试的表单抽屉 -->
    <el-drawer
      class="set-exam"
      :title="currentExam.course_name"
      size="45%"
      :visible.sync="setExamDrawer"
      :direction="drawerDirection"
      :before-close="handleClose">
      <hr>
      <br>

      <!-- 排课表单部分 -->
      <!-- <div class="setcoursetitle">排课</div> -->
      <el-form
        :model="setExamForm"
        :rules="setExamRules"
        ref="setExamForm">
      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- 监考老师： -->
          <el-form-item
            label="监考老师："
            prop="examTeacherName">
            <el-select v-model="setExamForm.examTeacherName" placeholder="请选择教师" size="small">
              <el-option
                v-for="item in teacherList"
                :key="item"
                :label="item"
                :value="item"></el-option>
            </el-select>
            <!-- <el-input
              size="small"
              v-model="setExamForm.examTeacherName">
            </el-input> -->
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- 考试地点： -->
          <el-form-item
            label="考试地点："
            prop="examClassroom">
            <el-input
              size="small"
              v-model="setExamForm.examClassroom">
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="10">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- 考试日期： -->
          <el-form-item
            label="考试日期："
            prop="examDay">
            <el-date-picker
              v-model="setExamForm.examDay"
              type="date"
              size="small"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12" :offset="0">
          <!-- <i>*</i> -->
          <!-- 考试时间： -->
          <el-form-item
            label="考试时间："
            prop="examStartTime">
            <el-time-select
              placeholder="起始时间"
              v-model="setExamForm.examStartTime"
              size="small"
              :picker-options="{
                start: '08:00',
                step: '00:30',
                end: '16:30'
              }">
            </el-time-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            label=""
            prop="examEndTime">
            至&nbsp;&nbsp;&nbsp;&nbsp;
            <el-time-select
              placeholder="结束时间"
              v-model="setExamForm.examEndTime"
              size="small"
              :picker-options="{
                start: '09:00',
                step: '00:30',
                end: '18:30',
                minTime: setExamForm.examStartTime
              }">
            </el-time-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-button type="school" class="submit" size="small" @click="setExamSubmit()">提交</el-button>
      <el-button type="success" size="small" plain @click="setExamDrawer = false;">取消</el-button>
      <br><br>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { toDateString } from '@/utils/time.js'
import { getAllTeachers } from '@/utils/dropdown.js'
export default {
  data () {
    // 验证教室格式
    var checkClassroom = (rule, value, cb) => {
      // 教的unicode码就是\u6559
      const regRoom = /^(\u6559)[\u4e09,\u56db,\u4e94]\d(0|1)\d/

      if (regRoom.test(value)) {
        return cb()
      }

      cb(new Error('请输入正确的教室名，样例格式：教三101'))
    }

    return {

      setExamRules: {
        examTeacherName: [
          { required: true, message: '请输入监考老师', trigger: 'blur' }
        ],
        examClassroom: [
          { required: true, message: '请输入考试地点', trigger: 'blur' },
          { validator: checkClassroom, trigger: 'blur' }
        ],
        examDay: [
          { required: true, message: '请选择考试日期', trigger: 'change' }
        ],
        examStartTime: [
          { required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        examEndTime: [
          { required: true, message: '请选择结束时间', trigger: 'change' }
        ]
      },

      examTable: [],
      currentPage: 1,
      totalCourse: 100,
      // 搜索框部分
      searchValue: '',
      searchMethod: '1',
      // 控制抽屉的可见性
      setExamDrawer: false,
      drawerDirection: 'rtl',
      // 选中的课程来排课
      currentExam: {},
      // 安排考试的表单
      setExamForm: {
        id: 0,
        examDay: '',
        examStartTime: '',
        examEndTime: '',
        examTeacherName: '',
        examClassroom: ''
      },
      teacherList: []
    }
  },
  async created () {
    this.getCourseList()
    this.teacherList = await getAllTeachers()
  },
  methods: {
    handleClose (done) {
      // this.$confirm('确认关闭？')
      //   .then(_ => {
      //     done();
      //   })
      //   .catch(_ => {});
      this.changeImg = ''
      this.previewImg = ''
      done()
    },
    // 搜索所有匹配到的课程
    searchCourse () {
      // 通过课程名搜索
      this.getCourseList()
    },
    // 获取所有的课程
    // 相当于页面中的那个选择方式为全局的变量改变
    async getCourseList () {
      if (this.searchMethod == 1) {
        const { data: res } = await this.$http.post(`exam/all/getExamList?page=${this.currentPage - 1}&rows=10&courseName=${this.searchValue}`)
        console.log(res)
        if (!res.state) return
        this.examTable = []
        this.foreachObj(res.detail)
        this.totalCourse = res.detail.total
      }
      // 通过学院名搜索
      else if (this.searchMethod == 2) {
        const { data: res } = await this.$http.post(`exam/all/getCourseList?page=${this.currentPage - 1}&rows=10&schoolName=${this.searchValue}`)
        console.log(res)
        if (!res.state) return
        this.examTable = []
        this.foreachObj(res.detail)
        this.totalCourse = res.detail.total
      }
    },
    // 更改页码，进行导航
    async handleCurrentChange (val) {
      // console.log(val)
      this.currentPage = val
      this.getCourseList()
    },

    // 展开安排考试抽屉
    async expandSetExamDrawer (exam) {
      this.setExamDrawer = true
      this.currentExam = exam
      this.setExamForm.id = exam.id
    },

    // 安排考试提交按钮实现
    async setExamSubmit () {
      this.$refs.setExamForm.validate(valid => {
        if (!valid) return
        var exam = {}
        exam.id = this.setExamForm.id
        exam.examTeacherName = this.setExamForm.examTeacherName
        exam.examClassroom = this.setExamForm.examClassroom
        exam.examDay = this.setExamForm.examDay
        exam.examTime = this.setExamForm.examStartTime + '-' + this.setExamForm.examEndTime
        console.log(exam)
        this.$http({
          method: 'post',
          url: '/exam/admin/updateExam',
          data: exam
        }).then(res => {
          const data = res.data
          console.log(data)
          if (!data.state) return this.$message.error(data.msg)
          this.$message.success(data.msg)
          this.setExamDrawer = false
          this.getCourseList()
          this.setExamForm = {
            id: 0,
            examDay: '',
            examStartTime: '',
            examEndTime: '',
            examTeacherName: '',
            examClassroom: ''
          }
        })
      })
    },

    // drop掉考试安排
    dropExam (exam) {
      this.$confirm('此操作将去除该考试安排, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.post(`exam/admin/deleteExam?id=${exam.id}`)
        if (!res.state) return this.$message.error(res.msg)
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getCourseList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    // 数据安排和填充
    foreachObj (data) {
      data.list.forEach(item => {
        var obj = {
          // 主键
          id: 0,
          // 课程编号
          course_teacher_num: '',
          // 课程名称
          course_name: '',
          // 专业名称
          class_name: '',
          // 学院名称
          school_name: '',
          // 学分
          credict: '',
          create_time: '',
          update_time: '',
          // 是否被安排
          is_arrange_exam: false,
          /// /
          // 只有被安排了才会有下面的字段
          /// /
          // 考试地点
          exam_classroom: '-',
          // 监考老师
          exam_teacher_name: '-',
          // 考试日期
          exam_day: '-',
          // 考试时间
          exam_time: '-'
        }
        obj.id = item.id
        obj.course_teacher_num = item.course_teacher_num
        obj.course_name = item.course_name
        obj.class_name = item.class_name
        obj.school_name = item.school_name
        obj.credict = item.credict
        obj.create_time = toDateString(item.create_time)
        obj.update_time = toDateString(item.update_time)
        obj.is_arrange_exam = item.is_arrange_exam
        if (item.is_arrange_exam == 1) {
          obj.isArrange = '已安排'
          obj.exam_classroom = item.exam_classroom
          obj.exam_teacher_name = item.exam_teacher_name
          obj.exam_day = toDateString(item.exam_day)
          obj.exam_time = item.exam_time
        } else {
          obj.isArrange = '未安排'
        }
        // console.log(obj)
        this.examTable.push(obj)
      })
    }
  }
}
</script>

<style lang="less" scoped>
.search-bar {
  margin-top: 20px;

  .el-select /deep/ .el-input {
    width: 110px;
  }
}

.course-list {
  margin-top: 20px;

  .el-table {

    .book-img {
      height: 100px;
    }
  }

  .el-pagination {
    margin: 12px 0;
    float: right;
  }
}

.set-exam {
  font-size: 14px;

  .el-row {
    margin-left: 10px !important;
    margin-bottom: 20px;

    i {
      color: red;
    }

    .el-input {
      width: 200px;
    }
  }

  .el-button.submit {
    margin-left: 120px;
  }
}
</style>
